import React, { useState, useEffect, useRef } from "react";
import { Form, Button, Input, Affix, Select, message, Space, Switch, Drawer, Row, Col } from "antd";
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { useModelAssociateMapping, useModelAssociateType} from "@/components";
import cmdbres from "@/data/cmdbres";
import hcpiam from "@/data/hcpiam";
import request, {requestIAM} from '@/utils/request';
import regexpUtil from "@/utils/regexpUtil";
import hcpUtils from "@/utils/hcpUtils";

const { uniqueIdentificationRegexp } = regexpUtil;
const user = hcpUtils.getUser();
const CreateRelation = ({ history, visible, setVisible, onCreateFinish }) => {
    const [loading, setLoading] = useState(false);
    const [mapping] = useModelAssociateMapping();
    const [{associateTypeData}] = useModelAssociateType();
    const [sourceModelData, setSourceModelData] = useState([]);
    const [targeteModelData, setTargeteModelData ] = useState([]);
    const [sourceModelKeyData, setSourceModelKeyData] = useState();
    const [targeteModelKeyData, setTargeteModelKeyData] = useState();
    const [conditionData, setConditionData] = useState(["="]);
    const [selectTypeValues, setSelectTypeValues] = useState({});
	const [form] = Form.useForm();

    const queryKindModule = async () => {
        try {
            let res = await request({
                ...cmdbres.queryKindModule,
            });
            if (res && res.code == 200) {
                setSourceModelData(res.data);
            }
        } catch (error) {
            console.log(error);
        }
    }

    const queryModelFilelds = async (moduleId, setData) => {
        try {
            setData();
            let res = await request({ 
                ...cmdbres.queryModelPropertyList,
                data: {
                    queryFilter: {
                        EQ: {
                            cmModuleId: moduleId,
                        },
                    }
                }
            });
            if (res && res.code == 200) {
                setData(res.data);
            } else {
                setData([]);
            }
        } catch (error) {
            setData([]);
        }
    }

    useEffect(() => {
        if(visible) {
            queryKindModule();
        }
    }, [visible]);

	const onFinish = async (fieldsValue) => {
        setLoading(true);
        let param = {
            moduleAssociateCode: fieldsValue.moduleAssociateCode,
            moduleAssociateName: fieldsValue.moduleAssociateName,
            description: fieldsValue.description,
            namespace: 'default',
            author: user.staffName,
            srcModuleId: '',
            srcModuleCode: '',
            srcId: '',
            ...selectTypeValues
        }
        if(isOpen) {
            param.conditions = [{
                srcModuleAssociateKey: fieldsValue.srcModuleAssociateKey,
                destModuleAssociateKey: fieldsValue.destModuleAssociateKey,
                associateCondition: fieldsValue.associateCondition,
            }]
        }
		let res = await request({
			...cmdbres.createModelAssociate,
			data: param
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success("新建关联成功！");
			if (typeof onCreateFinish == "function") onCreateFinish(res);
		}
	};

	const changeType = (type, value, option) => {
        let selectType = {...selectTypeValues};
        if(option) {
            Object.assign(selectType, option);
        } else {
            selectType[type] = value;
        }
        setSelectTypeValues(selectType);
	}

    const handleClose = () => {
        setVisible(false);
    }

    const [isOpen, setIsOpen] = useState(false);
    const [isDisabled, setIsDisabled] = useState(false);
    const handleChange = (value) => {
        setIsOpen(value);
    }

    return (
        <Drawer 
            className="drawer-table-columns create-field"
            title={'新建关联'}
            placement={'right'}
            width={600}
            onClose={handleClose}
            visible={visible}
            footer={null}
        >
            <Form
                className="hcp-drawer-form"
                form={form}
                labelCol={{ span: 5}}
                wrapperCol={{ span: 17 }}
                name="basic"
                onFinish={onFinish}
            >
                 <Form.Item 
                    label="唯一标识"
                    name="moduleAssociateCode"
                    rules={[
                           {
                            required: true,
                            message: '唯一标识不能为空',
                        },
                        uniqueIdentificationRegexp(256),
                    ]}
                    extra={
                        <p style={{ color: "#999999" }}>
                            请填写以字母开头，数字、字母、下划线，横线的组合
                        </p>
                    }
                    style={{ marginBottom: 5 }}
                    >
                    <Input placeholder="请输入唯一标识" maxLength={256} />
                </Form.Item>
                <Form.Item 
                    label="名称" 
                    name="moduleAssociateName" 
                    rules={[{required: true,message: '请输入字段名称'}]}
                >
                    <Input placeholder="请输入字段名称" maxLength={64} />
                </Form.Item>
                <Form.Item
                    label="源模型"
                    name="sourceModel"
                    key="sourceModel"
                    rules={[{required: true,message: '请选择源模型'}]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value, option) => {
                            console.log(value);
                            changeType('srcModuleId', value, {
                                srcModuleId: option.key,
                                srcModuleCode: option.value,
                                srcModuleName: option.name
                            });
                            form.setFieldsValue({targeteModel: undefined});
                            let data = sourceModelData?.filter(item => item.cmModuleId !== option.key);
                            setTargeteModelData(data);
                            // queryModelFilelds(option.key, setSourceModelKeyData);
                        }}
                        showSearch
                    >
                        {
                            sourceModelData?.map((item, index) => (
                                <Select.Option
                                    key={item.cmModuleId}
                                    value={item.moduleCode}
                                    name={item.moduleName}
                                >
                                    {item.moduleName}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="目标模型"
                    name="targeteModel"
                    key="targeteModel"
                    rules={[{required: true,message: '请选择目标模型'}]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value, option) => {
                            changeType('destModuleId', value, {
                                destModuleId: option.key,
                                destModuleCode: option.value,
                                destModuleName: option.name
                            });
                            // queryModelFilelds(option.key, setTargeteModelKeyData);
                        }}
                        showSearch
                    >
                        {
                            targeteModelData?.map((item, index) => (
                                <Select.Option
                                    key={item.cmModuleId}
                                    value={item.moduleCode}
                                    name={item.moduleName}
                                >
                                    {item.moduleName}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="关联类型"
                    name="associateType"
                    key="associateType"
                    rules={[{required: true,message: '请选择关系类型'}]}
                >
                     <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value) => changeType('associateType', value)}
                    >
                        {
                             associateTypeData?.map((item, index) => (
                                <Select.Option
                                    key={item.associateTypeCode}
                                    value={item.associateTypeCode}
                                    disabled={item.associateTypeCode == "cm_mainline"}
                                >
                                    {item.name}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item
                    label="源-目标约束"
                    name="modelMapping"
                    key="modelMapping"
                    rules={[{required: true,message: '请选择源-目标约束'}]}
                >
                    <Select
                        placeholder="请选择"
                        style={{ width: "100%", marginRight: 10 }}
                        onChange={(value) => {
                            changeType('mapping', value);
                            if(value == 'N-N') {
                                setIsOpen(false);
                                setIsDisabled(true);
                            } else {
                                setIsDisabled(false);
                            }
                        }}
                    >
                        {
                            mapping?.map((item, index) => (
                                <Select.Option
                                    key={index}
                                    value={item}
                                >
                                    {item}
                                </Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                {/* <Form.Item
                    label="模型关联条件"
                    name="open"
                    required
                    initialValue={false}
                >
                    <Switch
                        disabled={isDisabled}
                        checkedChildren="开启"
                        unCheckedChildren="关闭"
                        onChange={handleChange}
                        checked={isOpen}
                    />
                </Form.Item>
                {isOpen && <Row style={{margin: '0 8.33333333% 0 20.83333333%'}}>
                    <Col span={10}>
                        <Form.Item
                            name="srcModuleAssociateKey"
                            rules={[{required: true,message: '请选择源模型Key'}]}
                            wrapperCol={22}
                        >
                            <Select
                                placeholder="请选择源模型Key"
                                style={{ width: "95%", marginRight: 10 }}
                                loading={!sourceModelKeyData}
                                showSearch
                            >
                                {
                                    sourceModelKeyData?.map((item, index) => (
                                        <Select.Option
                                            key={index}
                                            value={item.propertyKey}
                                        >
                                            {item.propertyKey}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                        </Col>
                        <Col span={4}>
                            <Form.Item
                                name="associateCondition"
                                rules={[{required: true,message: '请选择关系条件'}]}
                                wrapperCol={22}
                                initialValue={"="}
                            >
                                <Select
                                    placeholder="请选择"
                                    style={{ width: "90%", marginRight: 10 }}
                                >
                                    {
                                        conditionData?.map((item, index) => (
                                            <Select.Option
                                                key={index}
                                                value={item}
                                            >
                                                {item}
                                            </Select.Option>
                                        ))
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={10}>
                        <Form.Item
                            name="destModuleAssociateKey"
                            rules={[{required: true,message: '请选择目标模型Key'}]}
                            wrapperCol={22}
                        >
                            <Select
                                placeholder="请选择目标模型Key"
                                style={{ width: "95%", marginRight: 10 }}
                                loading={!targeteModelKeyData}
                                showSearch
                            >
                                {
                                    targeteModelKeyData?.map((item, index) => (
                                        <Select.Option
                                            key={index}
                                            value={item.propertyKey}
                                        >
                                            {item.propertyKey}
                                        </Select.Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                </Row>
                } */}
                <Form.Item
                    label="描述"
                    name="description"
                    key="description"
                >
                    <Input.TextArea />
                </Form.Item>
                <div className="modal-body-footer">
                    <Space>
                        <Button type="primary" htmlType="submit" loading={loading}>提交</Button>
                        <Button onClick={handleClose}>取消</Button>
                    </Space>
                </div>
            </Form>
        </Drawer>
    );
};

export default CreateRelation;